import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

export default function Carousel() {
  // 广告列表
  let [adList, setAdList] = useState([]);
  // 当前广告序号
  let [curAd, setcurAd] = useState(0);

  useEffect(function () {
    let adList = [
      { aid: 10, pic: "/images/banner_01.jpg", href: "/" },
      { aid: 13, pic: "/images/banner_02.jpg", href: "/" },
      { aid: 16, pic: "/images/banner_03.jpg", href: "/" },
      { aid: 19, pic: "/images/banner_04.jpg", href: "/" },
    ];
    setAdList(adList);
  }, []);

  // 生命周期 在获得adList数据后 执行 自动轮播
  // 生命周期中 如果有定时器使用旧值 在新数据到来时摧毁
  useEffect(
    function () {
      let timer = null;
      if (adList.length) {
        timer = setInterval(function () {
          let i = curAd + 1;
          i = i >= adList.length ? 0 : i;
          setcurAd(i);
        }, 2500);
      }
      return function () {
        // 先销毁之前定时器 (旧数据)
        clearInterval(timer);
      };
    },
    [adList, curAd]
  );

  // 点击切换上一张
  function prev() {
    let i = curAd - 1;
    i = i < 0 ? adList.length - 1 : i;
    setcurAd(i);
  }

  // 点击切换下一张
  function next() {
    let i = curAd + 1;
    i = i >= adList.length ? 0 : i;
    setcurAd(i);
  }
  return (
    <>
      <div className="banner">
        <ul>
          {adList.map((ad, i) => (
            <li
              key={i}
              style={{
                background: `url(${ad.pic}) center 0 no-repeat`,
                display: i == curAd ? "block" : "none",
                zIndex: i == curAd ? "20" : "10",
              }}
            >
              <Link to={ad.href} className="link"></Link>
            </li>
          ))}
        </ul>
        {/* <!-- 左右箭头--> */}
        <span onClick={prev} className="cut prev"></span>
        <span onClick={next} className="cut next"></span>
        {/* <!-- 小圆点指示器--> */}
        <div className="indicator">
          {adList.map((ad, i) => (
            <a
              key={i}
              onClick={() => setcurAd(i)}
              href="/#"
              className={i == curAd ? "cur" : undefined}
            ></a>
          ))}
        </div>
      </div>
    </>
  );
}
